package com.link.base.base.apimiddle.controller;

import com.link.base.base.apimiddle.model.ApiMiddle;
import com.link.base.base.apimiddle.model.ApiMiddleCheck;
import com.link.base.base.apimiddle.service.ApiMiddleService;
import com.link.base.base.interinfo.model.InterInfo;
import com.link.base.base.interinfo.service.InterInfoService;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.cllog.LCLogger;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangMin
 * @date 2019/7/23
 * @comments
 */
@Controller
@RequestMapping("/link/apiMiddle")
public class ApiMiddleController extends BasicController<ApiMiddle> {

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private ApiMiddleService apiMiddleService;

    @Resource
    private InterInfoService interInfoService;

    @Override
    public BasicService<ApiMiddle> getBasicService() throws Exception {
        return apiMiddleService;
    }

    /**
     * 数据同步操作，从中间表中查询数据插入到正式表
     * @author zhenghongda
     * @date 
     * @param 
     * @return 
     */ 
    @RequestMapping(value = "/processData", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> processData(@RequestBody ApiMiddle data, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            Long id = data.getId();
            if (null == id) {
                result.put("success", false);
                result.put("result", "id不能为空！");
                return result;
            }
            ApiMiddle apiMiddle = apiMiddleService.queryById(id);
            if (!"New".equals(apiMiddle.getStatus()) && !"Failed".equals(apiMiddle.getStatus())) {
                result.put("success", false);
                result.put("result", "该状态不能执行同步操作！");
                return result;
            }
            List<ApiMiddle> list = new ArrayList<>();
            list.add(apiMiddle);
            apiMiddleService.processData(list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", "系统错误！");
        }
        return result;
    }

    /**
     * 外部接口调用入口：单条数据
     * @author zhenghongda
     * @date
     * @param
     * @return
     */
    @RequestMapping(value = "/syncData", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> syncData(@RequestBody ApiMiddle data, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            ApiMiddleCheck apiMiddleCheck = check(data);
            if (!apiMiddleCheck.isSuccess()) {
                result.put("success", false);
                result.put("message", apiMiddleCheck.getMessage());
                return result;
            }
            Long id = keyGenerateService.keyGenerate();
            data.setId(id);
            data.setStatus("New");
            apiMiddleService.insert(data);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", "系统错误！");
        }
        return result;
    }

    /**
     * 外部接口调用入口：多条数据
     * @author zhenghongda
     * @date
     * @param
     * @return
     */
    @RequestMapping(value = "/syncDataList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> syncDataList(List<ApiMiddle> datas, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    private ApiMiddleCheck check(ApiMiddle data) throws Exception {
        ApiMiddleCheck apiMiddleCheck = new ApiMiddleCheck();
        String interfaceId = data.getInterfaceId();
        if (StringUtils.isNull(interfaceId)) {
            apiMiddleCheck.setSuccess(false);
            apiMiddleCheck.setMessage("接口Id[interfaceId]不能为空！");
            return apiMiddleCheck;
        }

        if (StringUtils.isNull(data.getMessage())) {
            apiMiddleCheck.setSuccess(false);
            apiMiddleCheck.setMessage("同步数据[message]不能为空！");
            return apiMiddleCheck;
        }

        InterInfo param = new InterInfo();
        param.setInterCode(interfaceId);
        InterInfo interInfo = interInfoService.queryByCode(param);
        if (null == interInfo) {
            apiMiddleCheck.setSuccess(false);
            apiMiddleCheck.setMessage("接口Id[interfaceId]不存在！");
            return apiMiddleCheck;
        }
        // 服务
        data.setModule(interInfo.getInterModel());
        // 接口名称
        data.setInterfaceName(interInfo.getInterName());
        // 请求地址
        data.setRequestUrl(interInfo.getInterUrl());

        return apiMiddleCheck;
    }


    /**
     * 前边已处理，直接返回成功
     *
     * @param jsonObject
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/afterSyncData", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> afterSyncData(String jsonObject, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        result.put("result", "同步成功");
        result.put("success", true);
        return result;
    }

    /**
     * 根据module查询上一次同步记录
     *
     * @author 安小波
     * @date 2019/12/16 10:20
     * @param entity
     */
    @RequestMapping(value = "/queryLastRecordByModule")
    @ResponseBody
    public Map<String, Object> queryLastRecordByModule(@RequestBody ApiMiddle entity) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            ApiMiddle apiMiddle = apiMiddleService.queryLastRecordByModule(entity);
            result.put("success", true);
            result.put("result", apiMiddle);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/afterExecutedUpdate")
    @ResponseBody
    public Map<String, Object> afterExecutedUpdate(@RequestBody ApiMiddle entity) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            apiMiddleService.afterExecutedUpdate(entity);
            result.put("success", true);
            //result.put("result", "success");
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

}
